package yxy.game.pm2.active.command.sdk.weixin.onlinegift;

import org.joda.time.DateTime;
import yxy.apple.logger.Logger;
import yxy.cherry.data.bean.actzaixianfenxiang;
import yxy.cherry.game.base.message.MessageEmitterHandler;
import yxy.cherry.game.base.message.annotation.MessageSource;
import yxy.cherry.game.base.message.annotation.MessageType;
import yxy.game.pm2.Result;
import yxy.game.pm2.active.module.actdata.ActDataCenter;
import yxy.game.pm2.active.module.sdk.weixin.ActiveModule_在线礼包;
import yxy.game.pm2.bean.Currency;
import yxy.game.pm2.bean.mq.CCReason;
import yxy.game.pm2.command.Command;
import yxy.game.pm2.message.PackageMessage;
import yxy.game.pm2.message.SdkActiveMessage;
import yxy.game.pm2.message.SdkActiveMessage.WeiXinOnlineDrawRewardRequest;
import yxy.game.pm2.module.CurrencyHandle;

import java.util.Collection;
import java.util.Collections;

/**
 * 在线礼包
 * @author Dell
 *
 */
@MessageType(proto = Command.WeiXinOnlineDrawReward, classtype = SdkActiveMessage.WeiXinOnlineDrawRewardRequest.class)
public class CMD_Active_在线礼包_DrawReward extends Command<WeiXinOnlineDrawRewardRequest> {
	
	private static final Logger logger = Logger.create(CMD_Active_在线礼包_DrawReward.class);
	
	@Override
	public void execute(MessageSource messageSource, WeiXinOnlineDrawRewardRequest request) throws Exception {
		String pcode = messageSource.getTag();
		SdkActiveMessage.WeiXinOnlineDrawRewardResponse.Builder response = SdkActiveMessage.WeiXinOnlineDrawRewardResponse.newBuilder();
		
		ActiveModule_在线礼包 am = ActiveModule_在线礼包.get(pcode);
		if(am == null) {
			send(messageSource, response, Result.ActNoOpen);
			return;
		}
				
		int nextid = 1;
		if(am.getDrawids().size() > 0) {
			nextid = Collections.max(am.getDrawids()) + 1;			
		}
		actzaixianfenxiang data = ActDataCenter.getData(nextid, actzaixianfenxiang.class, pcode);
		if(data == null) {
			send(messageSource, response, Result.ActHadGet);
			return;
		}

		am.setDraw(DateTime.now());
		am.getDrawids().add(nextid);
		am.setOnline(0);
		am.set();

		Collection<Currency> curs = Currency.create(data.getRewardtype(), data.getRewardid(), data.getRewardnum());
		Collection<PackageMessage.Item> items = new CurrencyHandle().packItems(curs);
		response.addAllDisplay(items);
		
		new CurrencyHandle().addCurrency(pcode, CCReason.微信_活动_在线礼包, curs);
		
		send(messageSource, response, Result.Success);
	}

	private void send(MessageSource messageSource, SdkActiveMessage.WeiXinOnlineDrawRewardResponse.Builder response, Result result) {
		response.setResult(result.packResult());
		MessageEmitterHandler.getInstance().send(messageSource, response.build());
	}
	
}
